package com.bluejie.java.jdbc.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * Created by bluej on 2018/2/4.
 */
public class DBUtil {
    private static String user="bluej";
    private static String password = "bluej";
    private static String url = "jdbc:mysql://127.0.0.1:3306/java_jdbc?useUnicode=true&amp;characterEncoding=utf-8";

    private static String  sql = "select user_name from imooc_goddess where id =1;";
    public static void main(String[] args) {
        before();

        doDemo(sql);

        after();
    }

    /**
     * 查询数据Demo
     * @param sql
     */
    private static void doDemo(String sql){
        Connection connection = getDBConnection();
        Statement statement = null;
        try {
            statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);

            //遍历输出执行结果
            while (resultSet.next()){
                String userName = resultSet.getString("user_name");
                System.out.println("userName:"+userName);
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
        }finally {
            close(statement,connection);
        }
    }

    /**
     * 获取数据库连接
     * @return
     */
    private static Connection getDBConnection(){
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(url,user,password);

        }catch (Exception e){
            System.out.println(e.getMessage());
        }finally {
            return connection;
        }
    }

    /**
     * 关闭数据库连接
     * @param statement
     * @param connection
     */
    private static void close(Statement statement ,Connection connection){
        try {
            if (statement !=null){
                statement.close();
            }
            if (connection !=null){
                connection.close();
            }
        }catch (Exception e){
            System.out.println("DBConnection close error:"+e.getMessage());
        }

    }

    private static void before(){
        System.out.println("-------------start------------");
    }

    private static void after(){
        System.out.println("-------------end------------");
    }
}
